import lottie from 'lottie-miniprogram'
const { api } = require('../../../utils/api');

function initChart_pie (canvas, width, height, dpr, currentPage, componentId, imageCallback) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);

  var option = {
    backgroundColor: "transparent",
    series: [{
      label: {
        normal: {
          fontSize: 14
        }
      },
      type: 'pie',
      center: ['50%', '50%'],
      radius: ['20%', '40%'],
      data: [{
        value: 55,
        name: '管理与规划'
      }, {
        value: 20,
        name: '制作能力'
      }, {
        value: 10,
        name: '工具配置'
      }, {
        value: 20,
        name: '解决策略'
      }, {
        value: 38,
        name: '数据还原'
      }]
    }]
  };

  chart.on('finished', () => {
    const ecComponent = currentPage.selectComponent('#' + componentId);
    if (ecComponent) {
      setTimeout(() => {
        // 生成图片
        ecComponent.canvasToTempFilePath({
          success: res => {
            imageCallback(res.tempFilePath);
          },
          fail: res => console.log(res)
        });
      }, 500);
    } else {
      console.error("未找到饼图组件");
    }
  });

  chart.setOption(option);
  return chart;
}


function initChart_randar (canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr
  });
  canvas.setChart(chart);

  var option = {
    backgroundColor: "transparent",
    xAxis: {
      show: false
    },
    yAxis: {
      show: false
    },
    radar: {
      indicator: [{
        name: '观察力',
        max: 500
      },
      {
        name: '思维力',
        max: 500
      },
      {
        name: '实践能力',
        max: 500
      }
      ]
    },
    series: [{
      name: '预算 vs 开销',
      type: 'radar',
      data: [
        {
          value: [300, 400, 500],
          name: '开销',
          areaStyle: {
            color: '#c2d7da'
          }
        }
      ]
    }]
  };

  chart.setOption(option);

  chart.on('finished', () => {
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const ecComponent = currentPage.selectComponent('#mychart-dom-save');

    if (ecComponent) {
      setTimeout(() => {
        // 生成图片
        ecComponent.canvasToTempFilePath({
          success: res => {
            console.log("tempFilePath:", res.tempFilePath)
            currentPage.setData({
              'ec_randar.image': res.tempFilePath
            })
          },
          fail: res => console.log(res)
        });
      }, 500);
    } else {
      console.error("未找到雷达图组件");
    }
  });


  return chart;
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    gradeName: '',
    nickName: '',
    generateLog: '正在评估01题...',
    questionArray: [],
    isEvaluating: true,  // 控制是否显示评估过程
    totalScore: 0,       // 总分
    evaluationResult: '', // 评估结果描述
    imagesLoaded: false,  // 控制图片是否加载完成
    aspectRatio: '',      // 背景图宽高比
    totalChartCount: 5,
    renderCompletedChartCount: 0,
    windowHeight: 0,      // 设备屏幕高度
    userInfoStyle: '',    // user-info 的样式
    ec_randar: {
      onInit: initChart_randar,
      image: null
    },
    ec_pie1: {
      onInit: (canvas, width, height, dpr) => {
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        initChart_pie(canvas, width, height, dpr, currentPage, "mychart-pie1", (img) => {
          setTimeout(() => {
            currentPage.setData({
              'ec_pie1.image': img
            }, () => {
              currentPage.setData({
                'renderCompletedChartCount': currentPage.data.renderCompletedChartCount + 1
              })
            })
          }, 500);
        });
      },
      image: null
    },
    ec_pie2: {
      onInit: (canvas, width, height, dpr) => {
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        initChart_pie(canvas, width, height, dpr, currentPage, "mychart-pie2", (img) => {
          setTimeout(() => {
            currentPage.setData({
              'ec_pie2.image': img
            }, () => {
              currentPage.setData({
                'renderCompletedChartCount': currentPage.data.renderCompletedChartCount + 1
              })
            })
          }, 500);
        });
      },
      image: null
    },
    ec_pie3: {
      onInit: (canvas, width, height, dpr) => {
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        initChart_pie(canvas, width, height, dpr, currentPage, "mychart-pie3", (img) => {
          setTimeout(() => {
            currentPage.setData({
              'ec_pie3.image': img
            }, () => {
              currentPage.setData({
                'renderCompletedChartCount': currentPage.data.renderCompletedChartCount + 1
              })
            })
          }, 500);
        });
      },
      image: null
    },
    ec_pie4: {
      onInit: (canvas, width, height, dpr) => {
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        initChart_pie(canvas, width, height, dpr, currentPage, "mychart-pie4", (img) => {
          setTimeout(() => {
            currentPage.setData({
              'ec_pie4.image': img
            }, () => {
              currentPage.setData({
                'renderCompletedChartCount': currentPage.data.renderCompletedChartCount + 1
              })
            })
          }, 500);
        });
      },
      image: null
    },
    ec_pie5: {
      onInit: (canvas, width, height, dpr) => {
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        initChart_pie(canvas, width, height, dpr, currentPage, "mychart-pie5", (img) => {
          setTimeout(() => {
            currentPage.setData({
              'ec_pie5.image': img
            }, () => {
              currentPage.setData({
                'renderCompletedChartCount': currentPage.data.renderCompletedChartCount + 1
              })
            })
          }, 500);
        });
      },
      image: null
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    const nickName = options.nickName;
    const gradeName = options.gradeName;
    this.setData({ nickName, gradeName });

    // 获取设备信息
    const systemInfo = wx.getSystemInfoSync();
    const windowHeight = systemInfo.windowHeight;
    // 计算 user-info 的位置，设置在屏幕高度的 40% 处
    const userInfoStyle = `top: ${windowHeight * 0.4}px`;

    this.setData({
      windowHeight,
      userInfoStyle
    });
    // console.log(JSON.stringify(getApp().globalData.evaluationQuestionArray))
    let questionArray = getApp().globalData.evaluationQuestionArray || [];
    if (questionArray.length == 0) {
      questionArray = JSON.parse('[{"id":"1905585521354973186","no":"01","question":"<p>但是东方闪电</p>","title":"第三方斯蒂芬","options":[{"questionId":"1905585521354973186","name":"A.<p>aa</p>","value":0,"content":"<p>aa</p>","star":2,"checked":false},{"questionId":"1905585521354973186","name":"B.<p>bb</p>","value":1,"content":"<p>bb</p>","star":2,"checked":false},{"questionId":"1905585521354973186","name":"C.<p>cc</p>","value":2,"content":"<p>cc</p>","star":3,"checked":false},{"questionId":"1905585521354973186","name":"D.<p>dd</p>","value":3,"content":"<p>dd</p>","star":3,"checked":false}],"right":"C","answer":0,"power":"1905584568195194882"},{"id":"1905585623687602178","no":"02","question":"<p>asdfsadf</p>","title":"asdf","options":[{"questionId":"1905585623687602178","name":"A.<p>asdf</p>","value":0,"content":"<p>asdf</p>","star":5,"checked":false},{"questionId":"1905585623687602178","name":"B.<p>sdfgdfg</p>","value":1,"content":"<p>sdfgdfg</p>","star":5,"checked":false},{"questionId":"1905585623687602178","name":"C.<p>asdfsdf</p>","value":2,"content":"<p>asdfsdf</p>","star":5,"checked":false},{"questionId":"1905585623687602178","name":"D.<p>asgsdfs</p>","value":3,"content":"<p>asgsdfs</p>","star":5,"checked":false}],"right":"D","answer":0,"power":"1905584568195194882"}]')
    }
    console.log('评测报告页面 onLoad - 接收到的数据:', questionArray);
    this.setData({
      questionArray
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady () {
    console.log('评测报告页面 onReady - 当前数据:', this.data.questionArray);
    this.showLoading();
    this.startEvaluation();
    // 确保在页面渲染完成后调用
    setTimeout(() => {
      this.calculateContentHeight();
    }, 100);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage () {

  },

  /**
   * 呈现Lottie的加载动画
   */
  showLoading () {
    this.createSelectorQuery().select('#canvas').node(res => {
      const canvas = res.node;
      const ctx = canvas.getContext('2d');
      lottie.setup(canvas);
      lottie.loadAnimation({
        loop: true,
        autoplay: true,
        //animationData: animationData,
        path: 'https://qiniu.jingzhuzhixing.cn/xiaochengxu/lottie/generate-loading.json',
        rendererSettings: {
          context: ctx,
        },
      });
    }).exec()

    this.createSelectorQuery().select('#canvas2').node(res => {
      const canvas = res.node;
      const ctx = canvas.getContext('2d');
      lottie.setup(canvas);
      lottie.loadAnimation({
        loop: true,
        autoplay: true,
        //animationData: animationData,
        path: 'https://qiniu.jingzhuzhixing.cn/xiaochengxu/lottie/generate-loading2.json',
        rendererSettings: {
          context: ctx,
        },
      });
    }).exec()
  },

  /**
   * 开始评估过程
   */
  startEvaluation () {
    const { questionArray } = this.data;
    let currentIndex = 0;
    let totalScore = 0;

    const getPowerTree = async () => {
      try {
        const res = await api.get('/teaching/xiaochengxuTestPower/getTestPower');
        console.log('获取能力树原始数据：', res);

        // 转换为树状结构
        const buildTree = (items, parentId = '0') => {
          return items
            .filter(item => item.parentId === parentId)
            .map(item => ({
              ...item,
              children: buildTree(items, item.key)
            }));
        };

        const treeData = buildTree(res.result);
        console.log('转换后的树状结构：', treeData);
        return treeData;
      } catch (error) {
        console.error('获取能力树数据失败：', error);
        throw error;
      }
    }

    const updateLog = () => {
      if (currentIndex < questionArray.length) {
        const item = questionArray[currentIndex];
        const score = item.options[item.answer].star;
        totalScore += score;
        const questionNumber = String(currentIndex + 1).padStart(2, '0');

        this.setData({
          generateLog: `正在评估${questionNumber}题，得分${score}🌟`
        });

        currentIndex++;
        setTimeout(updateLog, 300);
      } else {
        // 评估完成，计算平均分并显示结果
        const averageScore = (totalScore / questionArray.length).toFixed(1);
        let resultText = '';

        if (averageScore >= 4.5) {
          resultText = '您的表现非常出色！';
        } else if (averageScore >= 3.5) {
          resultText = '您的表现良好！';
        } else if (averageScore >= 2.5) {
          resultText = '您的表现一般，还有提升空间。';
        } else {
          resultText = '建议您多加练习，提升技能水平。';
        }

        this.setData({
          generateLog: `评估完毕, 正在生成报告`
        });

        //保存评估数据
        api.post('/teaching/xiaochengxuReport/addTestReport', {
          reportValue: JSON.stringify({
            grade: this.data.gradeName,
            nickName: this.data.nickName,
            questions: this.data.questionArray
          })
        }).then(res => {
          const reportKey = res.message;
          // 跳转到报告页面
          wx.navigateTo({
            url: `/pages/evaluation/report-view/report-view?reportKey=${reportKey}&nickName=${encodeURIComponent(this.data.nickName)}&gradeName=${encodeURIComponent(this.data.gradeName)}`
          });
        })
        return;

        // 预加载图片
        const headerImage = 'http://daixiaoma.liziit.com/mp-report/header.png';
        const chartImage = 'http://daixiaoma.liziit.com/mp-report/chart.png';

        Promise.all([
          this.loadImage(headerImage),
          this.loadImage(chartImage)
        ]).then(() => {
          //拉取能力树配置
          getPowerTree().then(treeData => {

            // 图片加载完成后，延迟切换界面
            setTimeout(() => {
              this.setData({
                isEvaluating: false,
                totalScore: averageScore,
                evaluationResult: `评估完成！\n平均得分：${averageScore}🌟\n${resultText}`,
                imagesLoaded: true
              }, () => {
              });
            }, 1000);
          });
        });
      }
    };

    updateLog();
  },

  /**
   * 加载图片
   */
  loadImage (src) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: src,
        success: () => resolve(),
        fail: () => reject()
      });
    });
  },

  calculateContentHeight: function () {
    // 先获取图片信息
    wx.getImageInfo({
      src: 'http://daixiaoma.liziit.com/mp-report/chart.png',
      success: (imageInfo) => {
        console.log('图片信息:', imageInfo);
        const ratio = `${imageInfo.width} / ${imageInfo.height}`;
        console.log('宽高比:', ratio);
        this.setData({
          aspectRatio: ratio
        }, () => {
          // wx.pageScrollTo({
          //   scrollTop: 9999,
          //   duration: 300
          // });
        });
      },
      fail: (error) => {
        console.error('获取图片信息失败:', error);
      }
    });
  },

  // 返回首页
  goToHome () {
    wx.reLaunch({
      url: '/pages/home'
    });
  },

  // 监听返回按钮
  onBackPress () {
    this.goToHome();
    return true;
  }
})